package com.own.business.system.account.common.core;

import com.own.business.system.account.common.hook.AccountHook;
import com.own.component.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * AccountSpringHook
 *
 * @author chenxueli
 * @date 2022-09-12 13:29:00
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class AccountSpringHook implements ApplicationContextAware, ApplicationListener<ApplicationEvent> {

    private static final Map<String, AccountHook> ACCOUNT_HOOK_MAP = new LinkedHashMap<>(8);
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        AccountSpringHook.applicationContext = context;
    }

    /**
     * 获取对应的账号管理器
     */
    public AccountHook get(String type) {
        if (ACCOUNT_HOOK_MAP.containsKey(type)) {
            return ACCOUNT_HOOK_MAP.get(type);
        }
        throw new BusinessException("不支持的账号类型");
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            applicationContext.getBeansOfType(AccountHook.class).forEach((key, service) -> {
                var type = service.type().type();
                log.debug("账号信息接口===>【{}:{}】完成注册", type, key);
                ACCOUNT_HOOK_MAP.put(type, service);
            });
        }
    }

}
